#include "mission_manager.h"
#include "basic_root_mission.h"
#include "params.h"

mission_manager* mission_manager::instance = 0;

void mission_manager::set_general_mission(GeneralType type, mission *m)
{
	general_mission[type] = m;
}

std::vector<AI9::ActionBase*> mission_manager::act()
{
	LOG << "mission_manager::acting" << endl;
	assert(m_initialized);
	get_action_queue().clear();
	m_actioned = false;
	m_active_general = m_api.GetCntArmy()->general->type;

	mission *m = general_mission[get_api().GetCntArmy()->general->type];
	if (m == 0) 
	{
		LOG << "mission_manager::act() mission not found" << endl;
		return std::vector<AI9::ActionBase*>();
	}
	push_event(0, m, new basic_mission_event(m));
	while (event_list.size())
	{
		event_item item = event_list.back();
		event_list.pop_back();
		if (item.to)
			item.to->event_arrived(item.e);
		else
			LOG << "Event not handled " << item.e->get_type() << endl;
	}
	LOG << "mission_manager::act() returned, action_queue.size() = " << action_queue.size() << endl;
	return action_queue;
}

void mission_manager::initialize(AI9::UserAI *ai)
{
	LOG << "mission_manager::initializing" << endl;
	assert(!m_initialized);
	m_initialized = true;

	std::string strategy = params::get<std::string>("strategy", std::string("basic"));
	if (strategy == "basic")
	{
		gtype_list gl;
		for (int i = 0; i < (int) get_api().my_army.size(); ++i)
			gl.push_back(get_api().my_army[i]->general->type);

		basic_root_mission *sm = new basic_root_mission(0, gl);
		sm->execute();
		root_mission = sm;
		return;
	}

	fprintf(stderr, "undefined strategy %s\n", strategy.c_str());
	abort();
}
